%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%              Lab 2: Fourier Series and Fourier Transform                %
%                   EE558L: Section 1 (F: 1200-1440)                      %
%                            Dr. Nagaraj                                  %
%                     Author: Michael Spinali                             %
%                             813488956                                   %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% Create Fresh Environment
close all
clear all
clc

% Define Constants
F = 2E3;                        % Continous Time Frequency
Fs = 16E3;                      % Sampling Frequency
Ts = 1/Fs;                      % Sampling Period
Cycles = 30;                    % Number of Cycles to Display
n = 0:((Fs/F)*Cycles);          % Sample Time Vector
N = length(n);                  % Length of Sample Time Vector (n)
NFFT = 2^nextpow2(N);           % FFT length

%%%%%%%%%%%%%%% PART 1 %%%%%%%%%%%%%%%
figure('name','Part 1');
%Define Function
Xn = cos(2*pi*F*n*Ts);
subplot(3,1,1);
plot(n,Xn);
grid on;
axis([0 N -1.1 1.1]);
title(sprintf('x[n] = Cos(%0.3g*n)',2*pi*F*Ts),'fontsize',14);
xlabel('Time (samples)','fontsize',14);
ylabel('Amplitude','fontsize',14);


fxn=fftshift(fft(Xn,NFFT));
if(rem(NFFT,2) == 0)
  % N is even
  f = linspace(-Fs/2, (Fs/2) - (Fs/NFFT), NFFT);
else
  % N is odd
  f = linspace(-Fs/2, (Fs/2), NFFT);
end

subplot(3,1,2);
plot(f,abs(fxn));
grid on;
title(sprintf('%d Point FFT - X[f]',NFFT),'fontsize',14);
xlabel('Frequency(Hz)','fontsize',14);
ylabel('Amplitude','fontsize',14);

% Log Scale
subplot(3,1,3);
plot(f,20*log10(abs(fxn)));
grid on;
title(sprintf('%d Point FFT - X[f] (Log Scale)',NFFT),'fontsize',14);
xlabel('Frequency(Hz)','fontsize',14);
ylabel('Amplitude (dB)','fontsize',14);

%%%%%%%%%%%%%%% PART 2 %%%%%%%%%%%%%%%
figure('name','Part 2');
%Define Function
% The Sawtoothw as not sampled enough to sma. I normalized the amplitudes
%    by applying a small gain and DC shift
Xn = .57+.57*sawtooth(2*pi*F*n*Ts,1);
grid on;
subplot(3,1,1);
plot(n,Xn);
grid on;
axis([0 N -.1 1.1]);
title(sprintf('x[n] = sawtooth(%0.3g*n)',2*pi*F*Ts),'fontsize',14);
xlabel('Time (samples)','fontsize',14);
ylabel('Amplitude','fontsize',14);

fxn=fftshift(fft(Xn,NFFT));
if(rem(NFFT,2) == 0)
  % N is even
  f = linspace(-Fs/2, (Fs/2) - (Fs/NFFT), NFFT);
else
  % N is odd
  f = linspace(-Fs/2, (Fs/2), NFFT);
end

subplot(3,1,2);
plot(f,abs(fxn));
grid on;
title(sprintf('%d Point FFT - X[f]',NFFT),'fontsize',14);
xlabel('Frequency(Hz)','fontsize',14);
ylabel('Amplitude','fontsize',14);

% Log Scale
subplot(3,1,3);
plot(f,20*log10(abs(fxn)));
grid on;
title(sprintf('%d Point FFT - X[f] (Log Scale)',NFFT),'fontsize',14);
xlabel('Frequency(Hz)','fontsize',14);
ylabel('Amplitude (dB)','fontsize',14);